import type { RouteRecordRaw } from "vue-router";

const layouts = import.meta.glob("../layouts/*.vue", {
  eager: true,
  import: "default",
});
const views = import.meta.glob("../views/**/*.vue", {
  eager: true,
  import: "default",
});

function getLayoutRoutes() {
  return Object.entries(layouts).map(([key, moudel]) => {
    const route = getRoute(key, moudel);
    route.children = getChildrenRoute(route);
    return route;
  });
}

function getChildrenRoute(layoutRoute: RouteRecordRaw) {
  return Object.entries(views)
    .filter(([key, _]) => key.includes(layoutRoute.name as string))
    .map(([key, moudel]) => {
      return getRoute(key, moudel);
    });
}

function getRoute(key: string, moudel: any) {
  const name = key.replace(/.+layouts\/|.+views\/|\.vue/gi, "");
  return Object.assign(
    {
      path: "/" + name,
      name: name.replace("/", "-"),
      component: moudel,
    },
    moudel.route || null
  ) as RouteRecordRaw;
}

export default getLayoutRoutes;
